package com.example.smartstart.entity;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.example.smartstart.service.IStudentInfoService;

import java.util.ArrayList;
import java.util.List;

public class StudentInfoReadListener implements ReadListener<StudentInfo> {

    /**
     * 缓存的数据
     */
    private List<StudentInfo> cachedDataList = new ArrayList<>();

    private IStudentInfoService IStudentInfoService;

    public StudentInfoReadListener(IStudentInfoService IStudentInfoService) {
        this.IStudentInfoService = IStudentInfoService;
    }

    //  每读一行触发一次
    @Override
    public void invoke(StudentInfo studentInfo, AnalysisContext analysisContext) {
        System.out.println("读取到：" + studentInfo);
        cachedDataList.add(studentInfo);

    }

    // 都读完后触发一次
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("所有数据读取完毕");
        saveData();
    }

    /**
     * 将数据储存到数据库
     */
    private void saveData() {
        System.out.println(cachedDataList.size()+"条数据，开始存储数据库！");
        IStudentInfoService.saveStudentInfo(cachedDataList);
        System.out.println("存储数据库成功！");
    }
}
